--NPCManager is required for setting basic NPC properties
local npcManager = require("npcManager")

--Create the library table
local sampleNPC = {}
--NPC_ID is dynamic based on the name of the library file
local npcID = NPC_ID

--Defines NPC config for our NPC. You can remove superfluous definitions.
local sampleNPCSettings = {
	id = npcID,
	--Sprite size
	gfxheight = 28,
	gfxwidth = 50,
	--Hitbox size. Bottom-center-bound to sprite size.
	width = 64,
	height = 32,
	--Sprite offset from hitbox for adjusting hitbox anchor on sprite.
	gfxoffsetx = 0,
	gfxoffsety = 0,
	--Movement speed. Only affects speedX by default.
	speed = 1,
	--Collision-related
	noblockcollision = true,
	npcblock = false,
	npcblocktop = false, --Misnomer, affects whether thrown NPCs bounce off the NPC.
	playerblock = false,
	playerblocktop = false, --Also handles other NPCs walking atop this NPC.

	nohurt=false,
	nogravity = true,

	grabside=false,
	grabtop=false,

	isinteractable = true,
}

--Applies NPC settings
npcManager.setNpcSettings(sampleNPCSettings)

--Custom local definitions below


--Register events
function sampleNPC.onInitAPI()
	npcManager.registerEvent(npcID, sampleNPC, "onTickNPC")
	npcManager.registerEvent(npcID, sampleNPC, "onDrawNPC")
	registerEvent(sampleNPC, "onPostNPCKill")
end


local particles = require("particles")
local effect = particles.Emitter(0, 0, Misc.resolveFile("p_sparkles.ini"))


function sampleNPC.onTickNPC(v)
	--Don't act during time freeze
	if Defines.levelFreeze then return end
	local data = v.data
	--If despawned
	if v.despawnTimer <= 0 then
		--Reset our properties, if necessary
		data.initialized = false
		return
	end
	--Initialize
	if not data.initialized then
		--Initialize necessary data.
		v.InitialY = v.y
		v.upordown = true
		v.maxspeedz = 1.05
		v.speedY = -v.maxspeedz
		data.initialized = true
	end

	if v.upordown then
		v.speedY = v.speedY - 0.04
		v.speedY = math.max(v.speedY, -v.maxspeedz)
		if v.InitialY - 8 > v.y then
			v.upordown = false
		end
	else
		v.speedY = v.speedY + 0.04
		v.speedY = math.min(v.speedY, v.maxspeedz)
		if  v.InitialY + 8 < v.y then
			v.upordown = true
		end
	end
	effect:Attach(v)
end

function sampleNPC.onDrawNPC(v)
	effect:Draw(-75)
end

function sampleNPC.onPostNPCKill(Killed)
	if Killed.id == NPC_ID then
		SFX.play(59)
	end
end

--Gotta return the library table!
return sampleNPC